import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export const useNetworkStore = defineStore('network', () => {
  const ethernetData = ref([] as any[]);
  const firstInterfaceId = ref(''); //used for setting global DHCP settings
  const globalNetworkSettings = ref([] as any[]);
  const selectedInterfaceId = ref(); // which tab is selected
  const selectedInterfaceIndex = ref(0); // which tab is selected
  const domainState = ref('');
  const dnsState = ref('');
  const ntpState = ref('');

  const setDomainNameState = (domain: any) => {
    domainState.value = domain;
  };
  const setDnsState = (dns: any) => (dnsState.value = dns);
  const setEthernetData = (data: any) => (ethernetData.value = data);
  const setFirstInterfaceId = (id: any) => (firstInterfaceId.value = id);
  const setGlobalNetworkSettings = (data: { data: any }[]) => {
    globalNetworkSettings.value = data.map(({ data }) => {
      const {
        DHCPv4,
        HostName,
        IPv4Addresses,
        IPv4StaticAddresses,
        LinkStatus,
        MACAddress,
      } = data;
      return {
        defaultGateway: IPv4StaticAddresses[0]?.Gateway, //First static gateway is the default gateway
        dhcpAddress: IPv4Addresses.filter(
          (ipv4: { AddressOrigin: string }) => ipv4.AddressOrigin === 'DHCP',
        ),
        hostname: HostName,
        macAddress: MACAddress,
        linkStatus: LinkStatus,
        staticAddress: IPv4StaticAddresses[0]?.Address, // Display first static address on overview page
        useDnsEnabled: DHCPv4.UseDNSServers,
        useDomainNameEnabled: DHCPv4.UseDomainName,
        useNtpEnabled: DHCPv4.UseNTPServers,
      };
    });
  };
  const setNtpState = (ntp: any) => (ntpState.value = ntp);
  const setSelectedInterfaceId = (id: any) => (selectedInterfaceId.value = id);
  const setSelectedInterfaceIndex = (index: any) =>
    (selectedInterfaceIndex.value = index);

  const getEthernetData = async () => {
    return await api
      .get('/redfish/v1/Managers/bmc/EthernetInterfaces')
      .then((response) =>
        response.data.Members.map(
          (ethernetInterface: { [x: string]: any }) =>
            ethernetInterface['@odata.id'],
        ),
      )
      .then((ethernetInterfaceIds) =>
        api.all(
          ethernetInterfaceIds.map((ethernetInterface: string) =>
            api.get(ethernetInterface),
          ),
        ),
      )
      .then((ethernetInterfaces: any) => {
        const ethernetData = ethernetInterfaces.map(
          (ethernetInterface: { data: string }) => ethernetInterface.data,
        );
        const firstInterfaceId = ethernetData[0].Id;

        setEthernetData(ethernetData);
        setFirstInterfaceId(firstInterfaceId);
        // In order to avoid reset selectedInterfaceIndex when this value != 0
        if (selectedInterfaceIndex.value == 0)
          setSelectedInterfaceId(firstInterfaceId);
        setGlobalNetworkSettings(ethernetInterfaces);
      })
      .catch((error) => {
        console.log('Network Data:', error);
      });
  };
  const saveDomainNameState = async (domainState: any) => {
    setDomainNameState(domainState);
    const data = {
      DHCPv4: {
        UseDomainName: domainState,
      },
    };
    // Saving to the first interface automatically updates DHCPv4 and DHCPv6
    // on all interfaces
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${firstInterfaceId.value}`,
        data,
      )
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.domainName'),
        });
      })
      .catch((error) => {
        console.log(error);
        setDomainNameState(!domainState);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.domainName'),
          }) as string,
        );
      });
  };
  const saveDnsState = async (dnsState: any) => {
    setDnsState(dnsState);
    const data = {
      DHCPv4: {
        UseDNSServers: dnsState,
      },
    };
    // Saving to the first interface automatically updates DHCPv4 and DHCPv6
    // on all interfaces
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${firstInterfaceId.value}`,
        data,
      )
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.dns'),
        });
      })
      .catch((error) => {
        console.log(error);
        setDnsState(!dnsState);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.dns'),
          }) as string,
        );
      });
  };
  const saveNtpState = async (ntpState: any) => {
    setNtpState(ntpState);
    const data = {
      DHCPv4: {
        UseNTPServers: ntpState,
      },
    };
    // Saving to the first interface automatically updates DHCPv4 and DHCPv6
    // on all interfaces
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${firstInterfaceId.value}`,
        data,
      )
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.ntp'),
        });
      })
      .catch(() => {
        setNtpState(!ntpState);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.ntp'),
          }) as string,
        );
      });
  };
  const setSelectedTabIndex = (tabIndex: any) => {
    setSelectedInterfaceIndex(tabIndex);
  };
  const setSelectedTabId = async (tabId: any) => {
    setSelectedInterfaceId(tabId);
  };
  const saveIpv4Address = async (ipv4Form: any) => {
    const originalAddresses = ethernetData.value[
      selectedInterfaceIndex.value
    ].IPv4StaticAddresses.map(
      (ipv4: { Address: any; SubnetMask: any; Gateway: any }) => {
        const { Address, SubnetMask, Gateway } = ipv4;
        return {
          Address,
          SubnetMask,
          Gateway,
        };
      },
    );
    const newAddress = [ipv4Form];
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        { IPv4StaticAddresses: originalAddresses.concat(newAddress) },
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.ipv4'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.ipv4'),
          }) as string,
        );
      });
  };
  const editIpv4Address = async (ipv4TableData: any) => {
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        { IPv4StaticAddresses: ipv4TableData },
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.ipv4'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.ipv4'),
          }) as string,
        );
      });
  };
  const awakeDHCP = async () => {
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        {
          DHCPv4: {
            DHCPEnabled: true,
          },
        },
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.ipv4'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.ipv4'),
          }) as string,
        );
      });
  };
  const saveSettings = (interfaceSettingsForm: any) => {
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        interfaceSettingsForm,
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.network'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.network'),
          }) as string,
        );
      });
  };
  const saveDnsAddress = async (dnsForm: any) => {
    const newAddress = dnsForm;
    const originalAddresses =
      ethernetData.value[selectedInterfaceIndex.value].StaticNameServers;
    const newDnsArray = originalAddresses.concat(newAddress);
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        { StaticNameServers: newDnsArray },
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.dns'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.dns'),
          }) as string,
        );
      });
  };
  const editDnsAddress = async (dnsTableData: any) => {
    return api
      .patch(
        `/redfish/v1/Managers/bmc/EthernetInterfaces/${selectedInterfaceId.value}`,
        { StaticNameServers: dnsTableData },
      )
      .then(() => getEthernetData())
      .then(() => {
        return t('pageNetwork.toast.successSaveNetworkSettings', {
          setting: t('pageNetwork.dns'),
        });
      })
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageNetwork.toast.errorSaveNetworkSettings', {
            setting: t('pageNetwork.dns'),
          }) as string,
        );
      });
  };
  return {
    ethernetData,
    firstInterfaceId,
    globalNetworkSettings,
    selectedInterfaceId,
    selectedInterfaceIndex,
    domainState,
    dnsState,
    ntpState,
    setDomainNameState,
    setDnsState,
    setEthernetData,
    setFirstInterfaceId,
    setGlobalNetworkSettings,
    setNtpState,
    setSelectedInterfaceId,
    setSelectedInterfaceIndex,
    getEthernetData,
    saveDomainNameState,
    saveDnsState,
    saveNtpState,
    setSelectedTabIndex,
    setSelectedTabId,
    saveIpv4Address,
    editIpv4Address,
    awakeDHCP,
    saveSettings,
    saveDnsAddress,
    editDnsAddress,
  };
});
